import React, { useEffect, useRef, useState } from "react";

const SCROLLBAR_WIDTH = 16;

const CustomScrollbar: React.FC = () => {
  const [scrollTop, setScrollTop] = useState(0);
  const [scrollHeight, setScrollHeight] = useState(0);
  const [clientHeight, setClientHeight] = useState(0);
  const [isHover, setIsHover] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const dragStartY = useRef(0);
  const dragStartScrollTop = useRef(0);
  const containerRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    // 获取 #basiclayout 容器
    const container = document.getElementById('basiclayout');
    containerRef.current = container;
    if (!container) return;

    const handleScroll = () => {
      setScrollTop(container.scrollTop);
      setScrollHeight(container.scrollHeight);
      setClientHeight(container.clientHeight);
    };
    container.addEventListener("scroll", handleScroll);
    window.addEventListener("resize", handleScroll);
    handleScroll();

    // 定时器自动检测高度变化，保证初始和动态内容变化时滚动条长度正确
    const interval = setInterval(() => {
      if (
        container.scrollHeight !== scrollHeight ||
        container.clientHeight !== clientHeight
      ) {
        setScrollHeight(container.scrollHeight);
        setClientHeight(container.clientHeight);
      }
    }, 300);

    return () => {
      container.removeEventListener("scroll", handleScroll);
      window.removeEventListener("resize", handleScroll);
      clearInterval(interval);
    };
  }, [scrollHeight, clientHeight]);

  // 拖动相关
  useEffect(() => {
    if (!isDragging) return;
    const handleMouseMove = (e: MouseEvent) => {
      const container = containerRef.current;
      if (!container) return;
      const deltaY = e.clientY - dragStartY.current;
      const maxScroll = scrollHeight - clientHeight;
      const maxThumbMove = clientHeight - thumbHeight;
      let newThumbTop = (dragStartScrollTop.current / maxScroll) * maxThumbMove + deltaY;
      newThumbTop = Math.max(0, Math.min(newThumbTop, maxThumbMove));
      const newScrollTop = (newThumbTop / maxThumbMove) * maxScroll;
      container.scrollTop = newScrollTop;
    };
    const handleMouseUp = () => {
      setIsDragging(false);
    };
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, clientHeight, scrollHeight]);

  // 计算 thumbHeight
  const thumbHeight = Math.max((clientHeight / scrollHeight) * clientHeight, 40);
  const thumbTop = (scrollTop / (scrollHeight - clientHeight)) * (clientHeight - thumbHeight);

  // 这里再判断是否渲染
  if (scrollHeight <= clientHeight) return null;

  // 颜色逻辑：拖动时 #606060，悬停时 #a0a3a8，默认 #d1d3d6
  let thumbColor = "#d1d3d6";
  if (isDragging) {
    thumbColor = "#606060";
  } else if (isHover) {
    thumbColor = "#a0a3a8";
  }

  return (
    <div
      style={{
        position: "fixed",
        right: 0,
        top: 0,
        width: `${SCROLLBAR_WIDTH}px`,
        height: "100vh",
        zIndex: 9999,
        background: "#fff",
        borderTopLeftRadius: '8px',
        borderBottomLeftRadius: '0',
        boxShadow: '0 0 8px 0 rgba(0,0,0,0.04)',
        userSelect: "none",
        display: 'flex',
        alignItems: 'flex-start',
      }}
    >
      <div
        style={{
          position: "absolute",
          right: 2,
          width: `${SCROLLBAR_WIDTH - 4}px`,
          height: `${thumbHeight}px`,
          top: `${thumbTop}px`,
          background: thumbColor,
          borderRadius: "6px",
          transition: "background 0.2s",
          boxShadow: '0 1px 4px 0 rgba(0,0,0,0.08)',
          cursor: isDragging ? 'default' : 'pointer',
        }}
        onMouseDown={e => {
          setIsDragging(true);
          dragStartY.current = e.clientY;
          dragStartScrollTop.current = scrollTop;
        }}
        onMouseEnter={() => setIsHover(true)}
        onMouseLeave={() => setIsHover(false)}
      />
    </div>
  );
};

export default CustomScrollbar;